package cn.tom.config;

import cn.tom.tool.XResp;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author shuang.kou
 * AccessDeineHandler 用来解决认证过的用户访问需要权限才能访问的资源时的异常
 */
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
    /**
     * 当用户尝试访问需要权限才能的REST资源而权限不足的时候，
     * 将调用此方法发送401响应以及错误信息
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException)
            throws IOException {
        System.out.println("Denied ....=" + accessDeniedException.getMessage());
        accessDeniedException = new AccessDeniedException("Sorry you don not enough permissions to access it!");
        System.out.println("Denied2 ....=" + accessDeniedException.getMessage());

        response.setStatus(403);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(XResp.packJson(403, "权限不足，无法反问", accessDeniedException.getMessage()));
//        response.sendError(HttpServletResponse.SC_FORBIDDEN, accessDeniedException.getMessage());
        response.flushBuffer();
    }
}

